
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var socketio = require('socket.io');

var RedisStore = require('socket.io/lib/stores/redis')
    , redis  = require('socket.io/node_modules/redis');
/*
var sys = require('sys');
var redis = require('redis');

var subscriber = redis.createClient(6379, "119.207.203.170")


subscriber.subscribe('hoge channel');
subscriber.publish()
subscriber.on("message", function(channel, message)
{
   sys.puts(channel + " : " + message);
});*/

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = socketio.listen(server);

var pub = redis.createClient(6379, "119.207.203.170");
var sub = redis.createClient(6379, "119.207.203.170");
var store = redis.createClient(6379, "119.207.203.170");

var connection_ids = redis.createClient(6379, "119.207.203.170");
var socket_ids = [];

io.configure(function(){
    io.set('log level', 1);
    io.set('transports', [
        'websocket'
        , 'flashsocket'
        , 'htmlfile'
        , 'xhr-polling'
        , 'jsonp-polling'
    ]);
    io.set('store', new RedisStore({
        redis: redis
        , redisPub: pub
        , redisSub: sub
        , redisClient: store
    }));

    setInterval(function(){
        connection_ids.keys("*", function(err,keys)
        {
            keys.forEach(function(obj, opt)
            {
                connection_ids.get(obj, function(err, value)
                {
                    if(value != undefined) {
                        var arr = value.split(',');
                        if (arr[0] == "false") {

                            connection_ids.del(obj, function(err, val)
                            {
                                io.sockets.in(arr[1]).emit('out', obj);

                            });
                        }
                        else
                        {
                            console.log(obj + ": true");

                            connection_ids.get(obj,function(error, val)
                            {
                                connection_ids.set(obj, ["false", arr[1]]);
                            });
                        }



                    }
                });

            });
            /*  console.log(keys);
             connection_ids.get("C9CSIOGXLdrkWvdofhcC", function(err, val)
             {
             console.log(val);
             })*/
        });
    }, 30000);
    setInterval(function() {

        io.sockets.emit('ping', {msg : "live??"});


      /*  socket_ids.forEach(function(obj, opt)
        {
            //delete socket_ids[obj];
            console.log(obj);
        //    io.sockets.get(obj).disconnect();
        });*/

   },10000);
});

function registerUser(socket, nickname)
{

    socket.get('nickname',function(err,pre_nick){

        if(pre_nick != undefined ) delete socket_ids[pre_nick];

        socket_ids[nickname] = socket.id;


        socket.set('nickname',nickname,function(){

           // io.sockets.emit('userlist',{users:Object.keys(socket_ids)});

        });

    });
    socket.get('room',function(err, data)
    {
        connection_ids.set(nickname, ["true",data]);
    });
}


io.sockets.on('connection', function(socket){

   socket.on('join', function(data)
   {

       socket.join(data.roomname);
       socket.set('room', data.roomname);

       socket.get('room', function(error, room)
       {
          io.sockets.in(room).emit('join', data.userid);
           registerUser(socket, data.userid);


       });
   }) ;

    socket.on('pong', function(err,data)
    {

        socket.get('room', function(error, room) {
            if (err != null) {
                connection_ids.set(err.userid, ["true", err.roomname]);
            }
            else {
                console.log("fail");
            }
        });
        // console.log("pong" + message);
    });
   socket.on('message', function(message)
   {
      socket.get('room', function(error, room)
      {
          //socket.broadcast.emit('message', message);

          io.sockets.in(room).emit('message', message);

      }) ;
   });

    socket.on('whisper', function(message)
    {

        socket.get('room', function(error, room)
        {
            socket_id = socket_ids[message.userid];

            if(socket_id != undefined) {
                message.userid = '3';
                io.sockets.socket(socket_id).emit('message', message);
            }
        });

      /*  socket.get('room', function(error, room)
        {
            //socket.broadcast.emit('message', message);

            io.sockets.in(room).emit('message', message)

        }) ;*/

    });

    socket.on('disconnect',function(message)
    {

        socket.get('nickname', function(error, room)
        {
            //socket.broadcast.emit('message', message);


        }) ;
    });
});